package database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * Holds the pool of connections to the database
 * 
 * @author Tema
 */

public class DBUtils {

	private static Integer sync = 1;

	private DBUtils() {
	};

	public static Connection getConnection() throws DBException {
		synchronized (sync) {
			try {
				Context initContext;
				DataSource ds = null;
				initContext = new InitialContext();
				Context envContext = (Context) initContext
						.lookup("java:/comp/env");

				ds = (DataSource) envContext.lookup("jdbc/DBConnectionPool");
				Connection conn = ds.getConnection();
				if (conn == null) {
					throw new DBException(
							"MySQL Connection error: can't get the connection");
				}
				return conn;
			} catch (NamingException e) {
				throw new DBException(
						"Tomcat configuration error. Please configure Resourse name=\"jdbc/DBConnectionPool\"",
						e);
			} catch (SQLException e) {
				throw new DBException(
						"MySQL Connection error: can't get the connection", e);
			}
		}
	}

	public static void close(Connection conn) {
		if (conn == null) {
			return;
		}
		try {
			conn.close();
		} catch (Exception e) {
		}
	}

	public static void close(PreparedStatement stmt) {
		if (stmt == null) {
			return;
		}
		try {
			stmt.close();
		} catch (Exception e) {
		}
	}

	public static void close(ResultSet rs) {
		if (rs == null) {
			return;
		}
		try {
			rs.close();
		} catch (Exception e) {
		}
	}	
}
